﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::openTextByIODevice(const QString &fileName)
{
    QFile   file(fileName);
    //    aFile.setFileName(aFileName);
    //文件不存在
    if (!file.exists()){
        return false;
    }
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        return false;
    }
    ui->plainTextEdit->setPlainText(file.readAll());
    //ui->plainTextEdit->clear();
    while (!file.atEnd())
    {
        QByteArray line = file.readLine();//自动添加
        QString str=QString::fromLocal8Bit(line); //字节数组转换为字符串
        str.truncate(str.length()-1); //去除结尾增加的空行
        ui->plainTextEdit->appendPlainText(str);
    }
    file.close();

    ui->tabWidget->setCurrentIndex(0);
    return true;
}

bool MainWindow::saveTextByStream(const QString &fileName)
{
    QFile   aFile(fileName);
    //    aFile.setFileName(aFileName);

    if (!aFile.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QString str=ui->plainTextEdit->toPlainText();//整个内容作为字符串

    QByteArray  strBytes=str.toUtf8();//转换为字节数组
//    QByteArray  strBytes=str.toLocal8Bit();

    aFile.write(strBytes,strBytes.length());  //写入文件

    aFile.close();
    ui->tabWidget->setCurrentIndex(0);
    return  true;
}


void MainWindow::on_actionOpen_triggered()
{
    //打开文件
    QString path=QDir::currentPath();
    QString title="打开一个文件";
    QString filter="程序文件(*.h*.cpp);;文本文件(*.txt);;所有文件(*.*)";
    QString fileName=QFileDialog::getOpenFileName(this,title,"",filter);

    if(fileName.isEmpty()){
        return;
    }
    this->openTextByIODevice(fileName);
}

void MainWindow::on_actionsaveAs_triggered()
{
    QString curPath=QDir::currentPath();//获取系统当前目录
    QString dlgTitle="另存为一个文件"; //对话框标题
    QString filter="h文件(*.h);;c++文件(*.cpp);;文本文件(*.txt);;所有文件(*.*)"; //文件过滤器

    QString fileName=QFileDialog::getSaveFileName(this,dlgTitle,curPath,filter);

    if (fileName.isEmpty())
        return;

    saveTextByStream(fileName);
}
